package org.myontology.specialpages.helpers;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.myontology.controller.AttributeHolder;
import org.myontology.controller.AttributeLevel;
import org.myontology.controller.ValueHandler;

public class LanguageCheck {

	public static Logger logger = Logger.getLogger(LanguageCheck.class);
	
	
	public LanguageCheck() {
		Runtime r = Runtime.getRuntime();
		try {
			check = r.exec("aspell --lang=en -a");
			input = new InputStreamReader(check.getInputStream());
			output = new OutputStreamWriter(check.getOutputStream());
			new Reader().start();
			Thread.sleep(50);

		} catch (Exception e) {
			logger.error("error initializing aspell");
			logger.error("if LanguageCheck for labels shall be used, aspell has to be on the path");
		}
	}
	
	Process check;
	
	InputStreamReader input;
	OutputStreamWriter output;
	
	StringBuffer response = new StringBuffer();
	
	
	
	public static ValueHandler<String> LAST_LABEL_TRY = new ValueHandler<String>(AttributeLevel.SESSION,LanguageCheck.class);
	
	
	public boolean checkLabel(String label,AttributeHolder attr) {
		String lastLabel = LAST_LABEL_TRY.getValue(attr);
		
		if (lastLabel!=null && lastLabel.equals(label)) {
			return true;
		}
		LAST_LABEL_TRY.setValue(attr, label);
		return arePartsEnglish(label);
	}
	
	public boolean arePartsEnglish(String label) {
		List<String> parts = new ArrayList<String>();
		int trueCount=0;
		int falseCount=0;
		StringBuilder part = new StringBuilder();
		for (int i=0;i<label.length();i++) {
			boolean add=true;
			char c = label.charAt(i);
			if (c==' ' || Character.isUpperCase(c)) {
				if (part.toString().length()>1) {
					boolean isEnglish = isEnglish(part.toString());
					if (isEnglish)
						trueCount++;
					else
						falseCount++;
					if (c==' ')
						add=false;
					part=new StringBuilder();
				}
			}
			if (add)
				part.append(c);
		}
		boolean isEnglish = isEnglish(part.toString());
		if (isEnglish)
			trueCount++;
		else
			falseCount++;
		return trueCount>falseCount;
	}
	
	
	public boolean isEnglish(String label) {
		if (output==null)
			return true;
		try {
			output.write(label);
			output.write("\n");
			output.flush();
			Thread.sleep(10);
			String r = getResponse();
			if (r.indexOf('*')>-1)
				return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(e);
		}
		return false;
	}
	
//	public boolean isEnglish(String label) {

//		StringBuilder uri = new StringBuilder(); 
//	uri.append("http://dict.leo.org/ende?lp=ende&lang=de&searchLoc=-1&cmpType=relaxed&sectHdr=on&spellToler=on&chinese=both&pinyin=diacritic&search=")
//	.append(new URLEncoder().encode(label))
//	.append("&relink=on");
//		
//		GetMethod dictGet = new GetMethod(uri.toString());
//		HttpClient client = new HttpClient();
//		try {
//			client.executeMethod(dictGet);
//			String response = dictGet.getResponseBodyAsString();
//			

//			
//			if (response.indexOf("keine\nTreffer")==-1)
//				return true;
//		}
//		catch (Exception e) {
//			logger.error(e);
//			
//		}
//		finally {
//			if (dictGet!=null)
//				dictGet.releaseConnection();
//		}

//		return false;
//	}
	

	class Reader extends Thread {
		@Override
		public void run() {
			char c;
			try {
				c = (char)input.read();

				while (c>-1) {
					synchronized (this) {
						response.append(c);
					}
					c = (char)input.read();
				}
			} catch (IOException e) {

				logger.error(e);
			}
		}
	}
	
	
	
	public String getResponse() {
		String r="";
		synchronized (this) {
			r = response.toString();
			response = new StringBuffer();
		}
		return r;
	}
	
	public static void main (String args[]) {
		LanguageCheck c = new LanguageCheck();
		System.err.println(c.isEnglish("keyboard"));
		System.err.println(c.isEnglish("keyboardi"));
		System.err.println(c.isEnglish("myontology"));
	}
	
}
